import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';
import '../../providers/technique_provider.dart';
import '../../models/fishing_technique.dart';

class TechniquePage extends StatefulWidget {
  const TechniquePage({super.key});

  @override
  State<TechniquePage> createState() => _TechniquePageState();
}

class _TechniquePageState extends State<TechniquePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TextEditingController _searchController = TextEditingController();
  String _selectedDifficulty = 'all';

  final List<String> _categories = ['全部', '基础入门', '钓法技巧', '饵料配方', '装备选择', '钓点选择'];
  final List<String> _difficulties = ['all', '初级', '中级', '高级'];
  final List<String> _difficultyLabels = ['全部', '初级', '中级', '高级'];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _categories.length, vsync: this);
    _tabController.addListener(_onTabChanged);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<TechniqueProvider>().loadTechniques(refresh: true);
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        title: const Text('钓技学堂'),
        backgroundColor: Colors.blue[600],
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: _showSearchDialog,
          ),
          IconButton(
            icon: const Icon(Icons.filter_list),
            onPressed: _showFilterDialog,
          ),
        ],
        bottom: TabBar(
          controller: _tabController,
          isScrollable: true,
          indicatorColor: Colors.white,
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white70,
          tabs: _categories.map((category) => Tab(text: category)).toList(),
        ),
      ),
      body: Consumer<TechniqueProvider>(
        builder: (context, provider, child) {
          if (provider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          return TabBarView(
            controller: _tabController,
            children: _categories.map((category) {
              final techniques = provider.getFilteredTechniques(
                category,
                _selectedDifficulty,
                _searchController.text,
              );

              if (techniques.isEmpty) {
                return _buildEmptyState();
              }

              return RefreshIndicator(
                onRefresh: () => provider.loadTechniques(refresh: true),
                child: ListView.builder(
                  padding: const EdgeInsets.fromLTRB(16, 16, 16, 100), // 增加底部padding避免被底部导航栏遮挡
                  itemCount: techniques.length,
                  itemBuilder: (context, index) {
                    return _buildTechniqueCard(techniques[index]);
                  },
                ),
              );
            }).toList(),
          );
        },
      ),
    );
  }

  Widget _buildTechniqueCard(FishingTechnique technique) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: InkWell(
        onTap: () {
          context.push('/technique/${technique.id}');
        },
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 图片部分
            ClipRRect(
              borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
              child: Container(
                height: 180,
                width: double.infinity,
                child: technique.imageUrl.isNotEmpty
                    ? Image.network(
                        technique.imageUrl,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return _buildDefaultImage(technique.category);
                        },
                      )
                    : _buildDefaultImage(technique.category),
              ),
            ),
            
            // 内容部分
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题和难度标签
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Text(
                          technique.title,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(width: 8),
                      _buildDifficultyChip(technique.difficulty),
                    ],
                  ),
                  
                  const SizedBox(height: 8),
                  
                  // 副标题
                  if (technique.subtitle.isNotEmpty)
                    Text(
                      technique.subtitle,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  
                  const SizedBox(height: 12),
                  
                  // 标签
                  if (technique.tags.isNotEmpty)
                    Wrap(
                      spacing: 6,
                      runSpacing: 6,
                      children: technique.tags.take(3).map((tag) {
                        return Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.blue[50],
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.blue[200]!),
                          ),
                          child: Text(
                            tag,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.blue[700],
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  
                  const SizedBox(height: 12),
                  
                  // 底部信息
                  Row(
                    children: [
                      Icon(Icons.person, size: 14, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        technique.author,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                      const SizedBox(width: 16),
                      Icon(Icons.access_time, size: 14, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '${technique.estimatedReadTime}分钟',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                      const Spacer(),
                      Icon(Icons.visibility, size: 14, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '${technique.readCount}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                      const SizedBox(width: 12),
                      Icon(Icons.thumb_up, size: 14, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '${technique.likeCount}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDifficultyChip(String difficulty) {
    Color color;
    switch (difficulty) {
      case '初级':
        color = Colors.green;
        break;
      case '中级':
        color = Colors.orange;
        break;
      case '高级':
        color = Colors.red;
        break;
      default:
        color = Colors.grey;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Text(
        difficulty,
        style: TextStyle(
          fontSize: 12,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildDefaultImage(String category) {
    IconData icon;
    List<Color> colors;
    
    switch (category) {
      case '基础入门':
        icon = Icons.school;
        colors = [Colors.green[300]!, Colors.green[500]!];
        break;
      case '钓法技巧':
        icon = Icons.psychology;
        colors = [Colors.blue[300]!, Colors.blue[500]!];
        break;
      case '饵料配方':
        icon = Icons.science;
        colors = [Colors.orange[300]!, Colors.orange[500]!];
        break;
      case '装备选择':
        icon = Icons.build;
        colors = [Colors.purple[300]!, Colors.purple[500]!];
        break;
      case '钓点选择':
        icon = Icons.place;
        colors = [Colors.teal[300]!, Colors.teal[500]!];
        break;
      default:
        icon = Icons.waves;
        colors = [Colors.blue[300]!, Colors.blue[500]!];
    }

    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: colors,
        ),
      ),
      child: Center(
        child: Icon(
          icon,
          color: Colors.white,
          size: 48,
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.school_outlined,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无相关钓技内容',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '请尝试其他分类或搜索条件',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  void _showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('搜索钓技'),
          content: TextField(
            controller: _searchController,
            decoration: const InputDecoration(
              hintText: '输入关键词搜索...',
              prefixIcon: Icon(Icons.search),
            ),
            autofocus: true,
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {});
                Navigator.of(context).pop();
              },
              child: const Text('搜索'),
            ),
          ],
        );
      },
    );
  }

  void _showFilterDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('筛选条件'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('难度等级：'),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: _difficulties.asMap().entries.map((entry) {
                  final index = entry.key;
                  final difficulty = entry.value;
                  final label = _difficultyLabels[index];
                  
                  return FilterChip(
                    label: Text(label),
                    selected: _selectedDifficulty == difficulty,
                    onSelected: (selected) {
                      setState(() {
                        _selectedDifficulty = selected ? difficulty : 'all';
                      });
                    },
                  );
                }).toList(),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                setState(() {
                  _selectedDifficulty = 'all';
                });
                Navigator.of(context).pop();
              },
              child: const Text('重置'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _onTabChanged() {
    if (_tabController.indexIsChanging) return;
    final category = _categories[_tabController.index];
    context.read<TechniqueProvider>().loadTechniques(
      category: category == '全部' ? null : category,
      difficulty: _selectedDifficulty == 'all' ? null : _selectedDifficulty,
      searchQuery: _searchController.text.trim().isEmpty ? null : _searchController.text.trim(),
      refresh: true,
    );
  }
}